package zheng.mockit.plugin.http;

import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.handler.AbstractHandler;
import zheng.mockit.MessageHandler;
import zheng.mockit.plugin.http.message.MockitHttpRequestMessage;
import zheng.mockit.plugin.http.message.MockitHttpResponseMessage;
import zheng.mockit.plugin.http.utils.HttpParamUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by zcz on 16-7-29.
 */
public class MockitHttpServerHandler extends AbstractHandler {

    private MessageHandler messageHandler;

    public MockitHttpServerHandler(MessageHandler messageHandler) {
        this.messageHandler = messageHandler;
    }

    @Override
    protected void doHandle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        //1.先将接收到的请求发往TestCase用于验证。
        MockitHttpRequestMessage httpRequestMessage = new MockitHttpRequestMessage();
        httpRequestMessage.setUri(request.getRequestURI());
        httpRequestMessage.setParams(HttpParamUtils.getParamMap(request));
        messageHandler.sendMessage2TC(httpRequestMessage);

        //2.从TestCase接收消息，并将消息返回客户端。
        MockitHttpResponseMessage inMsg = (MockitHttpResponseMessage) messageHandler.getMessageFromTC();
        response.setStatus(inMsg.getStatusCode());
        response.getWriter().write(inMsg.getContent());
        response.getWriter().close();
    }
}
